const outRequire = require("lib/utils/outRequire.js");
const jwtToken = require("lib/utils/jwtToken.js");
const common = require("lib/utils/common.js");
const crypto = require("lib/utils/cryptoJs.js");
const db = require("db/user.js");

/** @name 登录 **/
exports.login = async (ctx) => {
	if (ctx.request.body.code) {
		await wxLogin(ctx);
	} else {
		await pcLogin(ctx);
	}
};

/** @name PC登录 **/
async function pcLogin(ctx) {
	if (ctx.requiredParams(["username", "password"])) return;
	const { username, password } = ctx.request.body;
	const listRes = await db.yd_find(username);
	console.log("listRes", listRes);
	const user = listRes[0];
	console.log("当前登录用户：", user);
	if (user) {
		if (crypto.decrypt(password) === crypto.decrypt(user.password)) {
			if (user.status === 0) {
				return ctx.fail("此账号已被锁定，你是不是做了不可描述的事情？-.-");
			}
			const token = await jwtToken.createToken({ username: user.username });
			ctx.session.token = token;
			ctx.session.userInfo = user;
			ctx.success(
				{
					uuid: user.uuid,
					username: user.username,
					nickname: user.nickname,
					avatar: user.avatar,
					gender: user.gender,
					note: user.note,
					role: user.role,
					status: user.status,
					lastTime: user.lastTime,
					createTime: user.createTime,
					updateTime: user.updateTime,
					token: token,
				},
				"欢迎进入"
			);
			// 更新登录时间
			const currentTime = common.YD_dateFormat();
			db.yd_updateLastTime({
				uuid: user.uuid,
				lastTime: currentTime,
				updateTime: currentTime,
			});
		} else {
			ctx.fail("账户密码错误！！！");
		}
	} else {
		ctx.fail("此账号并未注册哦！！！");
	}
}
/** @name 微信小程序登录 **/
async function wxLogin(ctx) {
	if (ctx.requiredParams(["code"])) return;
	const { code } = ctx.request.body;
	await outRequire
		.getOpenId(code)
		.then(async (res) => {
			const { openid } = JSON.parse(res); // {session_key, expires_in, openid}
			let queryRes = await db.yd_query(openid);
			if (queryRes.length) {
				await session(ctx, queryRes[0]);
			} else {
				let addRes = await db.yd_add([
					common.YD_generateUUID(),
					openid,
					common.YD_dateFormat("yyyy-MM-dd hh:mm:ss"),
					common.YD_dateFormat("yyyy-MM-dd hh:mm:ss"),
				]);
				if (addRes) {
					await db.yd_query(openid).then(async (res) => {
						session(ctx, res[0]);
					});
				} else {
					ctx.fail("新用户注册失败");
				}
			}
		})
		.catch((err) => {
			console.log(err);
			ctx.fail("openid获取异常");
		});
}

/** @name 查询用户信息-当前登录人 **/
exports.info = async (ctx) => {
	const { uuid } = ctx.session.userInfo;
	await db.yd_query(uuid).then(async (res) => {
		if (res.length) {
			const user = res[0];
			ctx.success({
				uuid: user.uuid,
				username: user.username,
				nickname: user.nickname,
				avatar: user.avatar,
				gender: user.gender,
				note: user.note,
				role: user.role,
				status: user.status,
				lastTime: user.lastTime,
				createTime: user.createTime,
				updateTime: user.updateTime,
				token: ctx.session.token,
			});
		} else {
			ctx.fail("用户信息查询失败");
		}
	});
};

/** @name 退出 **/
exports.logout = async (ctx) => {
	ctx.session.token = null;
	ctx.session.userInfo = null;
	ctx.success("退出成功");
};

/** @name 用户列表 **/
exports.list = async (ctx) => {
	const {
		username,
		gender,
		nickname,
		realname,
		phone,
		email,
		role,
		status,
		startTime,
		endTime,
	} = ctx.query;
	const options = {
		...common.YD_getPageDefault(ctx),
		username,
		gender,
		nickname,
		realname,
		phone,
		email,
		role,
		status,
		createTime: startTime
			? [`${startTime} 00:00:00`, `${endTime} 23:59:59`]
			: undefined,
	};
	const totalRes = await db.yd_count(options);
	const total = totalRes[0].count || 0;
	const rows = await db.yd_list(options);
	ctx.success({
		total,
		rows,
	});
};

/** @name 添加用户 **/
exports.add = async (ctx) => {
	if (ctx.requiredParams(["realname", "phone"])) return;
	const { realname, phone, gender, email, note } = ctx.request.body;
	const currentTime = common.YD_dateFormat();
	const options = {
		realname,
		phone,
		gender: common.YD_isUndefined(gender, 0),
		email,
		note,
		uuid: common.YD_generateUUID(),
		role: 1,
		status: 1,
		createTime: currentTime,
		updateTime: currentTime,
	};
	await db.yd_add(options);
	ctx.success("用户添加成功");
};

/** @name 编辑用户 **/
exports.edit = async (ctx) => {
	if (ctx.requiredParams(["realname", "phone"])) return;
	const { realname, phone, gender, email, note, uuid } = ctx.request.body;
	const currentTime = common.YD_dateFormat();
	const options = {
		realname,
		phone,
		gender: common.YD_isUndefined(gender, 0),
		email,
		note,
		updateTime: currentTime,
	};
	await db.yd_update(options, { uuid });
	ctx.success("用户编辑成功");
};

/** @name 删除用户 **/
exports.delete = async (ctx) => {
	if (ctx.requiredParams(["uuid"])) return;
	const { uuid } = ctx.request.body;
	await db.yd_delete(uuid);
	ctx.success("用户删除成功");
};

/** @name 简易查询全部用户列表 **/
exports.easyList = async (ctx) => {
	const rows = await db.yd_easyList();
	ctx.success({
		rows,
	});
};
